import sys,os,cgi,time
sys.path.insert(0, os.path.split(sys.path[0])[0])
import cfg
import cred
import web

def authorized(user,password,action='',tags=[],addr=''):
	if addr in web.addr_blacklist():
		return False
	realm = 'rivulet'
	pw = cred.get_pw(user,realm)
	basic_auth = bool(pw and pw==password)
	if not basic_auth:
		return False
	if action:
		return cred.action_auth(user,action,tags)
	else:
		return True

def header(banner=True,ct="text/html",action='',tags=[]):
	kind = os.getenv('AUTH_TYPE','')
	user = os.getenv('REMOTE_USER','')
	password = os.getenv('REMOTE_PASS','')
	value = os.getenv('AUTH_VALUE','')
	addr = os.getenv('REMOTE_ADDR','')
	
	for x in ['AUTH_TYPE','REMOTE_USER','REMOTE_PASS','AUTH_VALUE','REMOTE_ADDR']:
		os.unsetenv(x)

	if authorized(user,password,action,tags,addr):
		print "HTTP/1.1 200 ok"
		print 'WWW-Authenticate: Basic realm="rivulet"'
		print "Content-Type: %s" % ct
		print 
		if banner:
			env = cfg.get('cfg','meta').get('name','Rivulet')
			print """<html><head>
					<STYLE>
					<!--
					a {text-decoration:none}
					//-->
					</STYLE>
					</head>"""
			print """<table width="100%%"><tr><td width="80%%"><h1>%s</h1></td>
			<td width="20%%"><p align="right"><a href="logout.py">logout %s</a></p></td>
			</tr></table>""" % (env,user)
	else:
		print "HTTP/1.1 401 Unauthorized"
		print 'WWW-Authenticate: Basic realm="rivulet"'
		print "Content-Type: text/html"
		print
		if addr in web.addr_blacklist():
			print "<h1>Unauthorized addr</h1>"
		elif action:
			print "<h1>Unauthorized action</h1>"
		else:
			print "<h1>Unauthorized user</h1>"
		raise Exception('Unauthorized')
